package com.suxii.todomvi.presentation.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.suxii.todomvi.presentation.intent.TodoIntent
import com.suxii.todomvi.domain.model.Todo
import com.suxii.todomvi.domain.repository.TodoRepository
import com.suxii.todomvi.presentation.state.TodoDialogState
import com.suxii.todomvi.presentation.state.TodoState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class TodoViewModel @Inject constructor(
    private val todoRepository: TodoRepository
):ViewModel() {

    // 待办的状态
    private val _todoState = MutableStateFlow(TodoState())
    val todoState = _todoState.asStateFlow()

    // 弹窗显示的状态
    private val _todoDialogState:MutableStateFlow<TodoDialogState> = MutableStateFlow(
        TodoDialogState.Hidden)
    val todoDialogState = _todoDialogState.asStateFlow()

    init {
        todoRepository.queryAll().onEach {
                items ->
            _todoState.update {
                it.copy(items = items)
            }
        }.launchIn(viewModelScope)
    }



    fun invoke(intent: TodoIntent){
        when(intent){
            is TodoIntent.Delete -> viewModelScope.launch {
                todoRepository.delete(intent.todo)
            }
            is TodoIntent.DeleteByIds -> viewModelScope.launch {
                todoRepository.deleteByIds(intent.ids)
            }
            is TodoIntent.Insert -> viewModelScope.launch {
                todoRepository.insert(intent.todo)
            }
            TodoIntent.QueryAll -> TODO()
            is TodoIntent.Update -> viewModelScope.launch {
                todoRepository.update(intent.todo)
            }
        }
    }

    fun showEditDialog(todo: Todo){
        viewModelScope.launch {
            _todoDialogState.update { TodoDialogState.Editing(todo)}
        }
    }

    fun dismissDialog(){
        viewModelScope.launch {
            _todoDialogState.update { TodoDialogState.Hidden }
        }
    }

    private fun queryAll(){
        viewModelScope.launch {
            val list = todoRepository.queryAll()
        }
    }

}